import React, { useRef, useState } from 'react';
import Map, { MapRefProps } from '@/components/Map';
import {
  Typography,
  Button,
  FormInstance,
  Form,
  Input,
  Grid,
  Cascader,
} from '@arco-design/web-react';
import { useModal } from '@/components/Modal';
import { cloneDeep } from 'lodash-es';
import styles from './index.module.less';

const { Text, Paragraph } = Typography;

export type ListItemProps = {
  name?: string;
  value?: string;
  [key: string]: string;
};

export default function MapSearch({
  changeAddress,
}: {
  changeAddress: (returnAddressInfo: { [key: string]: string }) => void;
}) {
  const { hideModal } = useModal();
  const mapRef = useRef<MapRefProps>(null);
  const formRef = useRef<FormInstance>();
  const currentSelectProvice = useRef<string>('');
  const currentSelectCity = useRef<string>('');
  const currentDistrict = useRef<string>('');
  const [options, setOptions] = useState([]);

  const getAddressDetail = () => {
    const provice = options.find(
      (item) => item.adcode === currentSelectProvice.current
    );
    const city = provice.children.find(
      (item) => item.adcode === currentSelectCity.current
    );
    const district = city.children.find(
      (item) => item.adcode === currentDistrict.current
    );
    return {
      provice,
      city,
      district,
    };
  };

  const onOk = () => {
    const { address } = formRef.current.getFieldsValue();
    const { provice, city, district } = getAddressDetail();
    const returnAddressInfo = {
      provinceCode: provice.adcode,
      provinceName: provice.label,
      cityCode: city.adcode,
      cityName: city.label,
      districtCode: district.adcode,
      districtName: district.label,
      addressAll: provice.label + city.label + district.label + address,
      address: provice.label + city.label + district.label,
      lon: district.center.lng,
      lat: district.center.lat,
    };
    changeAddress(returnAddressInfo);
    hideModal();
  };

  // 添加市列表
  const addCityInProvice = (
    selectVal: string,
    cityList: Array<ListItemProps>
  ) => {
    const originOptions = cloneDeep(options);
    const currentProvice = originOptions.find(
      (item) => item.value === selectVal
    );
    currentProvice.children = cityList.map((item) => ({
      ...item,
      value: item.adcode,
      label: item.name,
    }));
    setOptions(originOptions);
    return originOptions;
  };

  // 添加地区列表
  const addDistrictInCity = (
    selectVal: string,
    districtList: Array<ListItemProps>
  ) => {
    const originOptions = cloneDeep(options);
    const currentProvice = originOptions.find(
      (item) => item.value === currentSelectProvice.current
    );
    const currentCity = currentProvice.children.find(
      (item) => item.value === selectVal
    );
    currentCity.children = districtList.map((item) => ({
      ...item,
      value: item.adcode,
      label: item.name,
      isLeaf: true,
    }));
    setOptions(originOptions);
    return originOptions;
  };

  const loadMore = (pathValue, level) => {
    return new Promise((resolve) => {
      if (+level === 1) {
        // 点击省
        currentSelectProvice.current = pathValue[0];
        mapRef.current?.getCityData(
          {
            value: pathValue[0],
          },
          (cityData) => {
            resolve(addCityInProvice(pathValue[0], cityData));
          }
        );
      } else {
        // 点击市
        currentSelectCity.current = pathValue[1];
        mapRef.current?.getDistrictData(
          {
            value: pathValue[1],
          },
          (districtData) => {
            resolve(addDistrictInCity(pathValue[1], districtData));
          }
        );
      }
    }) as Promise<Array<{ [key: string]: string }>>;
  };

  // 初始化省
  const initProviceData = (proviceData = []) => {
    const finallProviceData = proviceData.map((item) => ({
      ...item,
      value: item.adcode,
      label: item.name,
    }));
    setOptions(finallProviceData);
  };

  return (
    <Typography className={styles.page}>
      <Form ref={formRef} layout="vertical">
        <Paragraph className={styles.header}>
          <Text>设置活动地址</Text>
          <img
            className={styles.close}
            onClick={() => {
              hideModal();
            }}
            src={require('./img/close.png')}
          />
        </Paragraph>
        <Paragraph className={styles.content}>
          <Paragraph className={styles.search}>
            <Grid.Row gutter={24}>
              <Grid.Col span={10}>
                <Form.Item label={null} field="city">
                  <Cascader
                    placeholder="请选择"
                    className={styles.cascader}
                    bordered={false}
                    options={options}
                    loadMore={loadMore}
                    onChange={(value: Array<string>) => {
                      if (value.length === 3) {
                        // 地图查询地区
                        currentDistrict.current = value[2];
                        mapRef.current?.getAddressData({
                          value: value[2],
                        });
                      }
                    }}
                    showSearch
                    allowClear
                  />
                </Form.Item>
              </Grid.Col>
              <Grid.Col span={14}>
                <Form.Item label={null} field="address">
                  <Input placeholder={'请输入详细地址'} />
                </Form.Item>
              </Grid.Col>
            </Grid.Row>
          </Paragraph>
          <Map ref={mapRef} initProviceData={initProviceData} />
        </Paragraph>
        <Paragraph className={styles.footer}>
          <Button key="ok" type="primary" className={styles.ok} onClick={onOk}>
            确定
          </Button>
        </Paragraph>
      </Form>
    </Typography>
  );
}
